﻿using UnityEngine;
using System.Collections;

public class MonsterSpawner : MonoBehaviour {
    public GameObject monsterPrefab = null;
    public float[] spawnTime = {10.0f, 20.0f};
    float spawnTimeout = 5.0f;
    public float spawnDistance = 5.0f;
    public float predictionTime = 1.0f;
    public LayerMask wallLayerMask;
	// Use this for initialization
	void Start () {
        spawnTimeout = Random.Range(spawnTime[0], spawnTime[1]);
	}
	
	// Update is called once per frame
	void Update () {
        //Debug.Log("t");
		if (!BoatController.isDead){
	        spawnTimeout -= Time.deltaTime;
	        if (spawnTimeout <= 0)
	        {
	            int maxTryouts = 5;
	            bool encontrou = false;
	            Vector3 direction = new Vector3();
	            
	            for (int i = 0; i < maxTryouts && !encontrou; i++)
	            {
	                direction = new Vector3(Random.Range(-1.0f, 1.0f),
	                0, Random.Range(-1.0f, 1.0f));
	                Debug.Log("aqui1");
	                RaycastHit hit;
	                Ray ray = new Ray(transform.position, direction);
	                
	                if (Physics.Raycast(ray, out hit, spawnDistance, wallLayerMask))
	                {
	                   
	                }
	                else
	                {
	                    Debug.DrawRay(ray.origin, ray.direction * spawnDistance, Color.blue, 10);
	                    encontrou = true;
	                }
	            }
	             
	            if(encontrou)
	            {
	                Debug.Log("aqui3");
	                
	                GameObject go = Instantiate(monsterPrefab, 
	                    transform.position + (direction * spawnDistance), 
	                    Quaternion.identity) as GameObject;
	                Debug.Log("sp " + rigidbody.velocity);
	                Vector3 prediction = rigidbody.velocity * predictionTime;
	                go.GetComponent<Monster>().targetPosition = transform.position + prediction;
	                go.GetComponent<Monster>().targetObject = gameObject;
	                 
	            }
	            spawnTimeout = Random.Range(spawnTime[0], spawnTime[1]);
	        }
        }
	}

}
